﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;

namespace VBAConvertor.Parsers
{
    public class EnumReplacementParser : ILineParser
    {
        private static readonly Regex WordOp =
            new Regex(
                @"\b(?<word>\w+)\b",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        private static readonly Dictionary<string, string> _EnumDict;

        static EnumReplacementParser()
        {
            _EnumDict = new Dictionary<string, string>();
            var enumTypes = new List<Type>
                {
                    typeof (WdCursorType),
                    typeof (WdSpecialPane),
                    typeof (WdHeaderFooterIndex),
                    typeof (WdViewType),
                    typeof (WdCaptionLabelID),
                    typeof (WdCaptionNumberStyle),
                    typeof (WdSeparatorType),
                    typeof (WdWordDialog),
                    typeof (WdUnits),
                    typeof (WdBuiltinStyle),
                    typeof (WdInformation),
                    typeof (WdBreakType),
                    typeof (WdCollapseDirection),
                    typeof (WdFieldType),
                    typeof(WdDefaultTableBehavior),
                    typeof (WdLineWidth),
                    typeof (WdBorderType)
                };
            foreach (var type in enumTypes)
            {
                foreach (var val in Enum.GetNames(type))
                {
                    _EnumDict[val] = type.Name;
                }
            }
        }

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            success = WordOp.IsMatch(lineContent);
            if (!success) return lineContent;
            return WordOp.Replace(lineContent, match =>
                {
                    if (match.Success)
                    {
                        if (_EnumDict.ContainsKey(match.Groups["word"].Value))
                        {
                            return string.Format("{0}.{1}", _EnumDict[match.Groups["word"].Value],
                                                 match.Groups["word"].Value);
                        }
                        return match.Value;
                    }
                    throw new Exception();
                });
        }
    }
}
